// 引入合约的 ABI 和地址 文件
import crowd from '../build/contracts/UserGoods.json';
// 引入 web3.js 库
import Web3 from 'web3';

let web3Provider;   // 声明 web3 的区块链提供者
let web3js;         // 声明 web3 的连接对象
let contracts;      // 声明合约对象

export async function initWeb3() {
    try {
        web3Provider = new Web3.providers.HttpProvider("http://127.0.0.1:7545");
        // 获得 web3 对象
        web3js = new Web3(web3Provider);
        // 获得合约对象
        let netWorkID = await web3js.eth.net.getId()
        //得到当前部署的合约地址
        let address = crowd.networks[netWorkID].address
        //得到部署的合约对象
        contracts = new web3js.eth.Contract(crowd.abi, address)
        // 设置 Web3Provider
        contracts.setProvider(web3Provider);
    } catch (error) {
        console.error("初始化 Web3 失败:", error);
    }

}

//用户注册
export async function register(name, pwd) {
    try {
        // 获取账户信息
        const accounts = await web3js.eth.getAccounts()
        // 获取当前的 gas price
        const gasPrice = await web3js.eth.getGasPrice()
        // 调用合约的注册函数
        const tx = await contracts.methods.register(name, pwd).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 3000000 // 根据需要调整 gas limit
        });
        return tx.blockHash
    } catch (error) {
        console.log("注册失败：", error)
    }
}

// 用户登录（不需要发送交易，调用 view 函数）
export async function login(name, pwd) {
    try {
        const result = await contracts.methods.login(name, pwd).call();
        if (result.includes("成功")) {
            return true;
        } else {
            return false;
        }
    } catch (error) {
        console.error("登录失败:", error);
        return false;
    }
}

// 修改用户密码
export async function updatePwd(name, newPwd) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.updatePwd(name, newPwd).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 300000
        });

        return tx.transactionHash;
    } catch (error) {
        console.error("密码修改失败:", error);
        return null;
    }
}

//修改用户名称
export async function updateName(name, newName) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.updateName(name, newName).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 300000
        });

        return tx.transactionHash;
    } catch (error) {
        console.error("名称修改失败:", error);
        return null;
    }
}

//用户充值
export async function userIncrement(uid, value) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.userIncrement(uid, value).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 3000000 // 根据需要调整 gas limit
        });

        return tx.blockHash;
    } catch (error) {
        console.error("充值失败:", error);
        return null;
    }
}

// 获取单个用户信息
export async function getUser(name) {
    try {
        const userData = await contracts.methods.getUser(name).call();

        // 转换数据结构（Solidity 返回的数组和对象需要特殊处理）
        const formattedUser = {
            uid: parseInt(userData.uid),
            name: userData.name,
            values: parseInt(userData.values),
            goodsArr: userData.goodsArr.map(id => parseInt(id)),
            review: userData.review,
            filed: userData.filed
        };
        return formattedUser;
    } catch (error) {
        console.error("获取用户信息失败:", error);
        return null;
    }
}

// 添加商品到个人橱窗
export async function addUserGoods(uid, price) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.addUserGoods(uid, price).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 500000
        });
        return tx;
    } catch (error) {
        console.error("添加商品失败:", error);
        return null;
    }
}

//添加商品到交易所
export async function addGoodsArray(productId, price, duration) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.addGoodsArray(productId, price, duration).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 500000
        });

        return tx;
    } catch (error) {
        console.error("添加商品到交易所失败:", error);
        return null;
    }
}

//用户下架交易所商品
export async function deleteGoodsArray(productId) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.deleteGoodsArray(productId).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 500000
        });
        return tx;
    } catch (error) {
        console.error("下架商品失败:", error);
        return null;
    }
}


// 购买商品
export async function shopping(fromUid, toUid, productId) {
    try {
        const accounts = await web3js.eth.getAccounts();
        const gasPrice = await web3js.eth.getGasPrice();

        const tx = await contracts.methods.shopping(fromUid, toUid, productId).send({
            from: accounts[0],
            gasPrice: gasPrice,
            gas: 1000000  // 复杂操作需要更多 gas
        });
        return tx;
    } catch (error) {
        console.error("购买失败:", error);
        
        return null;
    }
}

//获取单个用户已上架商品
export async function getUserPushGoods(uid) {
    try {
        const goods = await contracts.methods.getUserPushGoods(uid).call();

        return goods.map(g => ({
            id: parseInt(g.id),
            price: parseInt(g.price),
            seller: parseInt(g.userid),
            endTime: parseInt(g.EndTime) * 1000 ,
        }));
    } catch (error) {
        console.error("获取用户商品列表失败:", error);
        return [];
    }
}

//返回单个用户所有商品
export async function getUserGoods(uid) {
    try {
        const goods = await contracts.methods.getUserGoods(uid).call();
        return goods.map(g => ({
            id: parseInt(g.id),
            price: parseInt(g.price),
            seller: parseInt(g.userid),
            endTime: parseInt(g.EndTime) * 1000 ,
            isPut:g.isPut
        }));
    } catch (error) {
        console.error("获取用户商品列表失败:", error);
        return [];
    }
}

// 获取所有上架商品
export async function getAllActiveGoods() {
    try {
        const goods = await contracts.methods.getAllUserPushGoods().call();

        return goods.map(g => ({
            id: parseInt(g.id),
            price: parseInt(g.price),
            seller: parseInt(g.userid),
            endTime: parseInt(g.EndTime) * 1000 ,
        }));
    } catch (error) {
        console.error("获取商品列表失败:", error);
        return [];
    }
}

//根据商品id返回商品
export async function getGoods(id) {
    try{
        const goods = await contracts.methods.getGoods(id).call();
        const shop = ({
            id: parseInt(goods.id),
            price: parseInt(goods.price),
            seller: parseInt(goods.userid),
            endTime: parseInt(goods.EndTime) * 1000 ,
        })
        return shop
    }catch (error) {
        console.error("获取用户商品列表失败:", error);
        return [];
    }
}

//根据用户id返回用户名称
export async function getUserByUid(uid) {
    try {
        const user = await contracts.methods.getUserByUid(uid).call();
        return user
    } catch (error) {
        console.error("获取用户名称失败:", error);
        return null;
    }
}
